package com.wanmait.recruitment.controller;

import com.wanmait.recruitment.mapper.AdminLoginIpMapper;
import com.wanmait.recruitment.mapper.AdminMapper;
import com.wanmait.recruitment.pojo.Admin;
import com.wanmait.recruitment.pojo.AdminLoginIp;
import com.wanmait.recruitment.service.AdminLoginIpService;
import com.wanmait.recruitment.service.AdminService;
import com.wanmait.recruitment.util.CookieUtil;
import com.wanmait.recruitment.util.IPUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.util.List;

@Controller
@RequestMapping("manage/admin")
public class AdminController {
    @Resource
    private AdminService adminService;
    @Resource
    private AdminLoginIpService adminLoginIpService;

    @RequestMapping("list")
    @ModelAttribute("admins")
    public List<Admin> list(){
        return adminService.findAll();
    }

    @GetMapping("login")
    public void getLogin(){}
    @PostMapping("login")
    public String login(Admin admin, HttpServletRequest request, HttpSession session){
        Admin loginAdmin = adminService.login(admin);
        if(loginAdmin!=null) {
            String ip = IPUtil.getIp(request);
            adminService.updateLoginCount(loginAdmin);
            loginAdmin.setLoginCount(loginAdmin.getLoginCount()+1);
            AdminLoginIp adminLoginIp = new AdminLoginIp();
            adminLoginIp.setIpAddress(ip);
            adminLoginIp.setAdmin(loginAdmin);
            adminLoginIpService.insert(adminLoginIp);
            session.setAttribute("admin",loginAdmin);
            return "redirect:/manage/index";
        }
        else{
            return "redirect:/manage/admin/login";
        }
    }
    @RequestMapping("exit")
    public String exit(HttpSession session){
        session.removeAttribute("admin");
        return "redirect:/manage/admin/login";
    }
    @RequestMapping("insert")
    @ResponseBody
    public Integer insert(Admin admin){
        Admin findAdmin = adminService.findByUsername(admin.getUsername());
        if(findAdmin==null){
            adminService.insert(admin);
            return 1;
        }
        else{
            return 0;
        }
    }
    @RequestMapping("update")
    @ResponseBody
    public void update(Admin admin){
        adminService.update(admin);
    }
    @RequestMapping("batchOpreate")
    @ResponseBody
    public void batchOpreate(@RequestParam("ids[]")Integer[] ids){
        adminService.batchOpreate(ids);
    }
    @RequestMapping("saveUid")
    @ResponseBody
    public void saveUid(String uid,HttpServletResponse response){
        CookieUtil.addCookie("uid",uid,"/manage/admin/list",3,response);
    }
}
